package com.modelscope.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.modelscope.ai.domain.dto.ArticleItemQueryCriteria;
import com.modelscope.ai.domain.entity.Article;
import com.modelscope.ai.domain.entity.ArticleItem;
import com.modelscope.ai.mapper.ArticleMapper;
import com.modelscope.ai.service.ArticleItemService;
import com.modelscope.ai.mapper.ArticleItemMapper;
import com.modelscope.ai.utils.AssertUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Administrator
 * @description 针对表【article_item】的数据库操作Service实现
 * @createDate 2024-03-15 10:09:32
 */
@RequiredArgsConstructor
@Service
public class ArticleItemServiceImpl extends ServiceImpl<ArticleItemMapper, ArticleItem> implements ArticleItemService {


    final ArticleMapper articleMapper;


    @Override
    public List<ArticleItem> queryAll(ArticleItemQueryCriteria criteria) {
        // 用来返回所有用户信息，便于测试
        return lambdaQuery().eq(ArticleItem::getPid, criteria.getPid())
                .like(StringUtils.isNotEmpty(criteria.getContent()), ArticleItem::getContent, criteria.getContent()).list();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addArticleItem(ArticleItem articleItem) {
        // 添加的时候，
        Article article = articleMapper.selectById(articleItem.getPid());
        AssertUtil.isNotEmpty(article, "合集id不能为空");

        // 整体数量+1
        article.setTotal(article.getTotal() + 1);
        articleMapper.updateById(article);

        save(articleItem);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateArticleItem(ArticleItem articleItem) {
        AssertUtil.isNotEmpty(articleItem.getId(), "id不应该为空");
        updateById(articleItem);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteArticleItem(List<Long> ids) {
        ids.forEach(item -> {
            ArticleItem articleItem = getById(item);
            AssertUtil.isNotEmpty(articleItem, "id不存在");
            Article article = articleMapper.selectById(articleItem.getPid());
            article.setTotal(article.getTotal() - 1);
            removeById(item); // 移除 id
            articleMapper.updateById(article); // 更新文章
        });
    }
}




